/**
** 说明：转换原始页面数据模型到页面结构模型，便于设置运营参数；
**/
var opLevel =
        {
            "title":"运营层级",
            "type":"string",
             "propertyOrder": 1000,
            "enum":["","1","2","3"],
            "options":{
                "enum_titles":["继承父级","集团","省级","地市级" ]
            }
        }  ;

//transform page mode to actual page schema obj:
function transToPageModeMeta(rawMetaObj){
	var pageMeta2={};
	pageMeta2["type"] ="object";
	for(var k in rawMetaObj){
		if(k === "pageBlocks"){
			//for(var kk in rawMetaObj[k]){
			//	if(kk === "properties"){
				if(!pageMeta2["properties"]) pageMeta2["properties"] = {};
				pageMeta2["properties"]['pageBlocks'] = {};

				pageMeta2["properties"]['pageBlocks']['title'] = "页面区域定义";
				pageMeta2["properties"]['pageBlocks']['type'] = "object";

				pageMeta2["properties"]['pageBlocks']["properties"] =  buildPageBlocks(rawMetaObj[k]);

			//	}
			//	else
			//		pageMeta2[kk] = rawMetaObj[k]['title'];
			//}
		}
		else{
			if(k === "pageVars"){
				pageMeta2["properties"]["pageVars"] = buildArray(rawMetaObj[k]);
			}
			else{
				pageMeta2[k] = rawMetaObj[k];
			}
		}
	}

	// console.log("page meta info:\n" + JSON.stringify(pageMeta2));
	// pageMeta2['properties']['distLevel'] = deepCopy({},opLevel);
	return JSON.stringify(pageMeta2);
	//return false;
}


function buildPageBlocks(rawPageBlocks){
	var ret = {};
	for(var b in rawPageBlocks){
		ret[b] = buildObject(rawPageBlocks[b]);
		//添加pageblock的运营层级
		ret[b]['properties']['distLevel'] = deepCopy({},opLevel);
	}
	return ret;
}

function buildObject(blockDef){
	var ret = {};
	for(var k in blockDef){
		if(k === "properties" ){
			var to = blockDef[k];
			if(to ){
				ret[k] = {};
				for(var pk in to){	 //for each prop
					var prop = to[pk];
					if(prop["type"]){
						var t = prop["type"];
						if(t === "object"){
							ret[k][pk] = buildObject(prop);
						}
						else if(pagemeta.extTypes.hasOwnProperty(t)){	//是自定义类型？
								var title = prop['title'];
								var clz = pagemeta.getWidgetCloneDef(t,prop);


								//to[pk] = clz.metaMetaDef;
								if(title)	clz.metaMetaDef['title'] = title;
								ret[k][pk] = clz.metaMetaDef;
							}
							else{	//json内置类型
								var bp = {};
								for(var tpk in prop){
									bp[tpk] = prop[tpk];
								}
								ret[k][pk] = bp;
							}
					}
				}
			}
			else
				ret[k] = b[k];
		}
		else{
			ret[k] = blockDef[k];
		}
	}
	if(blockDef["title"]) ret["title"] = blockDef["title"];
	ret["type"] = "object";

	return ret;
}


function buildArray(prop){
	var ret = {};
	for(var i in prop){
		if(i === "items"){
			ret[i] = buildObject(prop[i]);
		}
		else{
			ret[i] = prop[i];
		}
	}
	ret['type'] = "array";
	return ret;
}



    /**
    **  jsoneditor 对象初始化完毕后的处理函数，用于进行进一步的规范处理；
    **/
    function postMetaReadyFunc(){
        console.log("json editor is ready! :");

// 		window.$each(jsoneditor.root.schema,visitNode);
		var objs = jsoneditor.editors;
		if(objs){
			for(var o in objs){

			//检查：数组基于位置的授权和继承
				if(objs[o].options && objs[o].options.assignByIndex === true ){
// 					var tp = o.path;
					assignByIndexBy(objs[o]);
				}
				//"options":{ "assignByIndex":true }
	// 		var lastArray = "";
	// 		if()
// 			检查是否为多级编辑内容："multiLevelEdite":true     //默认为false
				if(objs[o].options.multiLevelEdite){
					multiLevelEditeBy(objs[o]);
				}
			}
		}
    }


	///////////////////数组位置授权处理函数段////////////////////////////////

	//检查：数组基于位置的授权和继承
	function assignByIndexBy(node){
		console.log(node.path);
		//TODO：需要检查数组元素最大数量和最小数量是否相同，不同提示用户并不做后续处理；

		//get obj's title area
		var tTitle = getObjDefTitleArea(node.jsoneditor,node.path);
		if(tTitle){
			var funcBut = getFuncButton(node.jsoneditor,"设置位置权限",function(){
// 				alert("TODO：处理的外部逻辑，设置完毕数据回传");

				//demo:only demo:)
				window.open('widget/ext/arraysetting_demo.html?path=xxx&arraySize=4');
			});
			tTitle.appendChild(funcBut);
		}
		//该位置下的运营层级设置将重置为“继承父级”且不能修改
		setOpLevelToTree(node.jsoneditor,node.path,"","",true);
	}

	/**
	**	在弹出窗口内设置完数组后，将最终数据回传给jsoneditor组件处理
	**/
	function assignByIndexCallback(path,settings){
		console.log(settings);
		//在这里接收数据并填充到处理扩展数据中；
		var output_schema = document.getElementById("ext_schema");
		if(output_schema){
			var jsn = output_schema.value;
			if(!jsn) jsn="{}";
			var jsnObj = JSON.parse(jsn);
			if(!jsnObj.assignByIndex) jsnObj.assignByIndex = {};
			jsnObj.assignByIndex[path] = settings;
			output_schema.value = JSON.stringify(jsnObj);
		}
	}



	///////////////////多级编辑处理函数段////////////////////////////////

	//检查是否为多级编辑内容："multiLevelEdite":true     //默认为false
	function multiLevelEditeBy(node){
		console.log(node.path);
		
		//get obj's title area
		var tTitle = getObjDefTitleArea(node.jsoneditor,node.path);
		if(tTitle){
			var funcBut = getFuncButton(node.jsoneditor,"设置发布地域",function(){
// 				alert("TODO：处理的外部逻辑，设置完毕数据回传");
				//demo:only demo:)
				window.open('widget/ext/multiLevelEdite_demo.html?path=xxx&arraySize=4');
			});
			tTitle.appendChild(funcBut);
		}
	}

	/**
	**	在弹出窗口内设置完数组后，将最终数据回传给jsoneditor组件处理
	**/
	function multiLevelEditeCallback(path,settings){
		console.log(settings);
		alert(path + ":" + settings);
		//在这里接收数据并填充到处理扩展数据中；
		var output_schema = document.getElementById("ext_schema");
		if(output_schema){
			var jsn = output_schema.value;
			if(!jsn) jsn="{}";
			var jsnObj = JSON.parse(jsn);
			if(!jsnObj.multiLevelEdite) jsnObj.multiLevelEdite = {};
			jsnObj.multiLevelEdite[path] = settings;
			output_schema.value = JSON.stringify(jsnObj);
		}
		//在这里接收数据并填充到处理扩展数据中；
	}






    function visitNode(k,v){
    	var tmppath = "root";

        //检查：数组基于位置的授权和继承
        	//"options":{ "assignByIndex":true }
		var lastArray = "";
// 		if()
        //检查是否为多级编辑内容："multiLevelEdite":true     //默认为false

			console.log(k+":"+v);
			if($isplainobject(v) || Array.isArray(v)){
				$each(v,visitNode);
			}
		}



// //对输出的页面参数定义json进行修订，修正运营层级权限的设置；
// var currNodeLevel = '1'; // 当前节点的运营权限级别，默认为1：集团；
// var nodeLevelStack = [];
// function setNodeLevel(nodeDef){
// 	if(nodeDef['distLevel']){
// 		nodeLevelStack.push(currNodeLevel);
// 		currNodeLevel = nodeDef['distLevel'];
// 	}
// 	else{
// 		currNodeLevel = nodeLevelStack[0];	//set to parent level
// 	}
// }
// function restoreNodeLevel(nodeDef){
// 	currNodeLevel = nodeLevelStack.pop();
// }

 // 	if(blockDef["title"]) ret["title"] = blockDef["title"];
	// ret["type"] = "object";

	// if(!ret['distLevel'])
	// 	ret['distLevel'] = currNodeLevel;
	// //restore node level
	// restoreNodeLevel(blockDef);
